<?php

// ==============================================================================
//
// This file is part of the WelSpeak.
//
// Create by Welfony Support <support@welfony.com>
// Copyright (c) 2012-2014 welfony.com
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//
// ==============================================================================

use Imagine\Image\Box;
use Imagine\Gd\Imagine;
use Imagine\Image\Point;
use Welfony\Welspeak\Core\Enum\SocialType;
use Welfony\Welspeak\File\FileUtility;
use Welfony\Welspeak\Repository\SocialRepository;
use Welfony\Welspeak\Repository\UserRepository;
use Welfony\Welspeak\Utility\Validation;
use Welfony\Welspeak\Utility\Util;

$app->post('/socials/login', function() use($app) {
    $reqData = getDataFromRequestWithJsonFormat();

    if (!isset($reqData['SocialId']) || empty($reqData['SocialId'])) {
        sendInvalidFieldResult('Social', 'id', 'missing_field');
    }
    $externalId = htmlspecialchars($reqData['SocialId']);
    $type = isset($reqData['Type']) ? intval($reqData['Type']) : SocialType::Facebook;
    $email = isset($reqData['Email']) ? htmlspecialchars($reqData['Email']) : '';
    $displayName = isset($reqData['DisplayName']) ? htmlspecialchars($reqData['DisplayName']) : '';
    $firstname = isset($reqData['Firstname']) ? htmlspecialchars($reqData['Firstname']) : '';
    $lastname = isset($reqData['Lastname']) ? htmlspecialchars($reqData['Lastname']) : '';
    $profileUrl = isset($reqData['ProfileURL']) ? htmlspecialchars($reqData['ProfileURL']) : '';
    $photoUrl = isset($reqData['PhotoURL']) ? htmlspecialchars($reqData['PhotoURL']) : '';
    $websiteUrl = isset($reqData['WebsiteURL']) ? htmlspecialchars($reqData['WebsiteURL']) : '';

    $socialData = array(
        'ExternalId' => $externalId,
        'PIN' => Util::genRandomNum(6),
        'Type' => $type,
        'Email' => $email,
        'DisplayName' => $displayName,
        'Firstname' => $firstname,
        'Lastname' => $lastname,
        'ProfileUrl' => $profileUrl,
        'PhotoUrl' => $photoUrl,
        'WebsiteUrl' => $websiteUrl
    );

    $user = UserRepository::findUserBySocialExternalId($socialData['ExternalId'], $socialData['Type']);
    if (!$user) {
        $email = empty($socialData['Email']) ? Util::genRandomEmail() : $socialData['Email'];
        $emailArr = explode('@', $email);
        $username = $emailArr[0];
        $password = Util::genRandomPassword();

        $user = UserRepository::findUserByUsernameOrEmail($email);
        if ($user) {
            $email = Util::genRandomEmail($username);
        }

        $userData = array(
            'Username' => $username,
            'Email' => $email,
            'Password' => $app->passHash->hashPassword($password),
            'CreatedDate' => date('Y-m-d H:i:s')
        );

        $success = false;
        $app->conn->beginTransaction();

        $newUserId = UserRepository::save($userData);
        if ($newUserId) {
            $socialData['UserId'] = $newUserId;
            $socialData['CreatedDate'] = date('Y-m-d H:i:s');

            $newSocialId = SocialRepository::save($socialData);
            if ($newSocialId) {
                $success = true;
                $app->conn->commit();
            } else {
                $app->conn->rollback();
                sendOperationFailedResult('social');
            }
        } else {
            sendOperationFailedResult('user');
        }

        if (!empty($socialData['PhotoUrl']) && Validation::isValidUrl($socialData['PhotoUrl'])) {
            $arrUrlSegment = parse_url($socialData['PhotoUrl']);
            $temp = explode('.', $arrUrlSegment['path']);
            $extension = end($temp);
            $hashFileName = base64_encode(date('Ymdhis') . uniqid());

            FileUtility::createDirs($app->config['app']['avatar_path'], $newUserId);
            $fileTargetPath = implode(DS, array($app->config['app']['avatar_path'], $newUserId, $hashFileName . '.' . $extension));

            $rstCurlAvatar = getImageFromUrl($socialData['PhotoUrl']);
            if ($rstCurlAvatar && getImageFileType($rstCurlAvatar)) {
                file_put_contents($fileTargetPath, $rstCurlAvatar);

                $imagine = new Imagine();
                $image = $imagine->open($fileTargetPath);
                $image->thumbnail(new Box(180, 180))->save($fileTargetPath);

                $data = array(
                    'AvatarUrl' => $app->config['app']['asset_base_url'] . implode('/', array('avatar', $newUserId, $hashFileName . '.' . $extension)),
                    'LastModifiedDate' => date('Y-m-d H:i:s')
                );
                UserRepository::update($newUserId, $data);
            }
        }

        $user = UserRepository::findUserById($newUserId);
    } else {
        $socialData['LastModifiedDate'] = date('Y-m-d H:i:s');
        $newSocialId = SocialRepository::update($socialData['ExternalId'], $socialData['Type'], $socialData);
    }

    sendResponse(array('success' => true, 'user' => $user));
});